package com.arpa.ntocc.basic.api.controller;


import com.arpa.core.web.MediaTypes;
import com.arpa.core.web.Result;
import com.arpa.ntocc.common.common.Page;
import com.arpa.ntocc.common.common.cache.PartyGroupCacheDO;
import com.arpa.ntocc.common.common.constant.StrConsts;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.ntocc.common.controller.BaseController;
import com.arpa.ntocc.common.domain.dto.RoleDTO;
import com.arpa.ntocc.common.domain.entity.Role;
import com.arpa.ntocc.common.domain.vo.RoleVO;
import com.arpa.ntocc.common.security.annotation.NeedLogin;
import com.arpa.ntocc.common.security.annotation.NoRepeat;
import com.arpa.ntocc.common.service.IRoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.*;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 用户角色 Controller
 * </p>
 *
 * @author LEO
 * @since 2019-12-05
 */
@Api(tags = "用户角色")
@RestController
@RequestMapping(value="/role", produces = "application/json;charset=UTF-8")
@Log4j2
public class RoleController extends BaseController {

   @Autowired
   private IRoleService  iRoleService;

    /**
     * 获取 用户角色 列表
     *
     * @param roleDTO
     * @param request
     * @return
     */
    @ApiOperation(value = "获取 用户角色 列表", notes = "获取 用户角色 列表")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = RoleVO.class))
    @NeedLogin
    @GetMapping()
    public Result list(RoleDTO roleDTO, HttpServletRequest request) {

        //获取登录用户所属机构
        PartyGroupCacheDO partyGroupCacheDO =  UserUtil.getBranch();
        if (partyGroupCacheDO.getLevel() > 0) {
            roleDTO.setBranchCode(UserUtil.getBranchCode());
        }
        RoleVO roleVOSum = iRoleService.queryListSum(roleDTO);
        List<RoleVO> roleVOList = iRoleService.queryList(roleDTO);

        Page returnPage = new Page(roleDTO.getPageNum(),roleDTO.getPageSize());
        returnPage.setRecords(roleVOList);
        returnPage.setTotal(roleVOSum.getTotal());
        returnPage.setSumObject(roleVOSum);
        return Result.ok().data(returnPage);
    }

    /**
     * 获取 角色权限
     *
     * @param roleDTO
     * @param request
     * @return
     */
    @ApiOperation(value = "获取 角色权限 列表", notes = "获取 角色权限 列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @GetMapping("resourceCodeList")
    public Result resourceCodeList(RoleDTO roleDTO, HttpServletRequest request) {
        //获取登录用户所属机构
        PartyGroupCacheDO partyGroupCacheDO =  UserUtil.getBranch();
        if (partyGroupCacheDO.getLevel() > 0) {
            roleDTO.setBranchCode(UserUtil.getBranchCode());
        }
        List<String> resourceCodeList = iRoleService.resourceCodeList(roleDTO);
        return Result.ok().data(resourceCodeList);
    }

    /**
     * 添加 用户角色
     *
     * @param entity Role
     * @param request
     * @return
     */
    @ApiOperation(value = "添加 用户角色 ", notes = "添加 用户角色 ")
    @ApiImplicitParams({
    @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
    @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @NoRepeat(time = 2000)
    @PostMapping()
    public Result create(@Validated Role entity, HttpServletRequest request) {
        try {
            entity.setBranchCode(UserUtil.getBranchCode());
            iRoleService.save(entity);
            return Result.ok("添加成功");
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
    * 获取用户角色详情
    *
    * @param code
    * @param request
    * @return
    */
    @ApiOperation(value = "获取用户角色详情", notes = "获取用户角色详情")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
        @ApiImplicitParam(name = "code", value = "用户角色code", paramType = "path", dataType = "String")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = Role.class))
    @NeedLogin
    @GetMapping(value = "/{code}")
    public Result role(@PathVariable String code, HttpServletRequest request) {
        try {
            Role entity = iRoleService.getOne(new QueryWrapper<Role>().lambda().eq(Role::getCode,code));
            return Result.ok().data(entity);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }


    /**
     * 修改用户角色
     *
     * @param entity 用户角色
     * @param request
     * @return
     */
    @ApiOperation(value = "修改用户角色", notes = "修改用户角色")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping()
    public Result update(@Validated Role entity, HttpServletRequest request) {
        if(StringUtils.isBlank(entity.getCode())){
            return Result.error("code不能为空");
        }
        int updateNum = iRoleService.updateByCode(entity);
        if(updateNum == 0){
            return Result.error("没有更新数据！code:"+entity.getCode());
        }else{
            return Result.ok("修改成功,更新"+updateNum+"条数据！");
        }
    }

    /**
     * 修改角色权限
     *
     * @param entity 用户角色
     * @param request
     * @return
     */
    @ApiOperation(value = "修改角色权限", notes = "修改角色权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping("updateRoleResource")
    public Result updateRoleResource(@RequestBody RoleDTO entity, HttpServletRequest request) {
        iRoleService.updateRoleResource(entity);
        return Result.ok("修改成功！");
    }

    /**
     * 删除 用户角色
     *
     * @param codes
     * @param request
     * @return
     */
    @ApiOperation(value = "删除 用户角色 ", notes = "删除 用户角色 ", produces = MediaTypes.JSON_UTF_8)
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
        @ApiImplicitParam(name = "codes", value = "codes", required = true, paramType = "query", dataType = "List")
    })
    @NeedLogin
    @DeleteMapping(value = "")
    public Result batchdel(@RequestParam List<String> codes, HttpServletRequest request) {
        try {
            iRoleService.batchdel(codes);
            return Result.ok("操作成功！");
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

 }
